Contents | Index | < Browse | Browse >
LETTERassertULETTER
Conditioned program aborting.
Overview
#include <assert.h>
assert(x);
int x; // Expression to be checked
Portability
ANSI
Description
The only macro defined in "assert.h" is assert. You can use this function
to increase stability of your program by using safety checks. If eg. a
function requires a parameter between 0 and 5 put the following at its
beginning:
{
assert(i>0 && i<5)
}
If the condition passed to assert is not true the program will exit with an
error message like
Assertion failed: i>0 && i<5, file "wrong.cc", line 1822
as long as you don't define the NDEBUG macro before usage of
assert. This will prevent assert's routines from being linked and save
running time and memory space. You should define NDEBUG only if you're
absolutely sure that your program does not contain any bugs. In any case,
avoid conditions which may cause unexpected events like below.
Example
FILE *fp;
assert(fp = fopen("S:supervisor-startup", "r")) // Very bad!
This will return a more or less useful error message if the program can't
find its configuration file. It will then quit, which is quite reasonable, but
sooner or later you will define NDEBUG and be surprised what happens.